package com.ruoyi.system.service.impl;

import com.ruoyi.domain.request.UserRequest;
import com.ruoyi.domain.utils.MD5Util;
import com.ruoyi.domain.utils.sendCode;
import com.ruoyi.system.mapper.RegistrationMapper;
import com.ruoyi.system.service.RegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @author 姚炜琦
 * @Classname RegistrationServiceImpl
 * @Description TODO
 * @Date 2022/10/21 9:16
 */
@Service
public class RegistrationServiceImpl implements RegistrationService {
    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String getCode(String phone) {
        // 生成随机六位数字验证码
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        String code = str.toString();
        // 存入Redis缓存中
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set("code",code);
        // 调用阿里短信接口发送短信
        sendCode.sendMsg(phone,code);
        // 返回前台回调
        return code;
    }

    @Override
    public String addUser(UserRequest userRequest) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        // 获取Redis中的验证码
        String code = ops.get("code");
        String clientCode = userRequest.getCode();
        if (!clientCode.equals(code)){
            return null;
        }
        // 用户密码加盐注册
        String newPassword = MD5Util.string2MD5(userRequest.getPassword());
        userRequest.setSalt(newPassword);
        // 注册用户
        registrationMapper.addUser(userRequest);
        return newPassword;
    }
}
